<template>
  <div class="bgc-default pad-20">
    <h2>基本信息</h2>
    <el-form :model="coupon" label-position="right" label-width="248px" :rules="rules" ref="coupon">
      <div class="bg-color-white pad-t-25" style="padding-bottom:100px;">
        <el-form-item label="券名称" prop="couponName">
          <div class="width-per-50"><el-input v-model="coupon.couponName" placeholder="券显示名称， 字数不多于10字" maxlength="10"></el-input></div>
        </el-form-item>
        <el-form-item label="面值" prop="cashAmount" v-if="coupon.couponType == 10">
          <div class="width-per-50">
            <el-input v-model="coupon.cashAmount" placeholder="请输入大于0的代金券面值" @keyup.native="coupon.cashAmount = checkInputPositiveNum(coupon.cashAmount)" maxlength="10">
              <template slot="append">元</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="优惠方式" prop="reduceAmount" v-if="coupon.couponType == 20">
          <div class="width-per-50">
            <el-row>
              <span>单笔订单适用商品金额满</span>
              <el-input v-model="coupon.fullAmount" @blur="coupon.fullAmount = checkInputNum(coupon.fullAmount)" style="width: 30%;" maxlength="10">
                <template slot="append">元</template>
              </el-input>
              <span>立减</span>
              <el-input v-model="coupon.reduceAmount" @blur="coupon.reduceAmount = checkInputNum(coupon.reduceAmount)" style="width: 40%;" maxlength="10">
                <template slot="append">元</template>
              </el-input>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="使用条件" prop="fullAmountFlag" v-if="coupon.couponType == 30">
          <div class="width-per-50">
            <div>
              <el-radio v-model="coupon.fullAmountFlag" @change="changeFullAmountFlag" label="0" style="width: 72%;">
                <span>单笔订单适用商品金额满</span>
                <el-input v-model="coupon.fullAmount" :disabled="fullAmountDisabled" @keyup.native="coupon.fullAmount = checkInputPositiveNum(coupon.fullAmount)" maxlength="10">
                  <template slot="append">元</template>
                </el-input>
              </el-radio>
            </div>
            <div><el-radio v-model="coupon.fullAmountFlag" @change="changeFullAmountFlag" label="1">不设门槛</el-radio></div>
          </div>
        </el-form-item>
        <el-form-item label="优惠方式" prop="discountPercent" v-if="coupon.couponType == 30">
          <div class="width-per-50">
            <el-row>
              <span>打</span>
              <el-input v-model="coupon.discountPercent" @keyup.native="coupon.discountPercent = checkInputNum(coupon.discountPercent, true)" style="width: 97%;" maxlength="6"><template slot="append">折</template></el-input>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="发放数量" prop="limitFlag">
          <div class="width-per-50">
            <div>
              <el-radio v-model="coupon.limitFlag" @change="changeLimitFlag" label="1" style="width:96.5%;">
                <el-input v-model="coupon.couponNum" :disabled="couponNumDisabled" @keyup.native="coupon.couponNum = checkInputPositiveNum(coupon.couponNum)" placeholder="请输入大于0的券发放总数量" maxlength="10">
                  <template slot="append">张</template>
                </el-input>
              </el-radio>
            </div>
            <el-radio v-model="coupon.limitFlag" @change="changeLimitFlag" label="0">不限数量</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="适用商品" prop="goodsRange">
          <div class="width-per-50">
            <div><el-radio v-model="coupon.goodsRange" @change="changeGoodsRange" label="1">所有商品</el-radio></div>
            <div><el-radio v-model="coupon.goodsRange" @change="changeGoodsRange" label="2">指定可使用商品</el-radio><el-button type="text" @click="showUseGoodsDialog" :disabled="useGoodsDisabled">选择商品</el-button></div>
            <div><el-radio v-model="coupon.goodsRange" @change="changeGoodsRange" label="3">指定不可使用商品</el-radio><el-button type="text" @click="showNotUseGoodsDialog" :disabled="notToUseGoodsDisabled">选择商品</el-button></div>
          </div>
        </el-form-item>
        <el-form-item label="使用范围说明" prop="couponRemark">
          <div class="width-per-50"><el-input v-model="coupon.couponRemark" placeholder="券的使用范围说明， 字数不多于10字" maxlength="10"></el-input></div>
        </el-form-item>
        <el-form-item label="有效时间" prop="validTimeType">
          <div class="width-per-50">
            <div>
              <el-radio v-model="coupon.validTimeType" @change="changeValidTimeType" label="1">
                <el-date-picker
                  v-model="coupon.validTimeArray"
                  :disabled="validTimeArrayDisabled"
                  type="daterange"
                  range-separator="至"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['00:00:00', '23:59:59']"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-radio>
            </div>
            <div class="mar-t-4">
              <el-radio v-model="coupon.validTimeType" @change="changeValidTimeType" label="2">
                领券当日起
                <el-input v-model="coupon.validFromToday" :disabled="validFromTodayDisabled" @keyup.native="coupon.validFromToday = checkInputPositiveNum(coupon.validFromToday)" placeholder="请填入最少为1天的天数" maxlength="10" />
                天之内有效
              </el-radio>
            </div>
            <div class="mar-t-4">
              <el-radio v-model="coupon.validTimeType" @change="changeValidTimeType" label="3">
                领券次日起
                <el-input v-model="coupon.validFromTomorrow" :disabled="validFromTomorrowDisabled" @keyup.native="coupon.validFromTomorrow = checkInputPositiveNum(coupon.validFromTomorrow)" placeholder="请填入最少为1天的天数" maxlength="10" />
                天之内有效
              </el-radio>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="封面图" prop="imageUrl">
          <div class="width-per-50">
            <div class="tips mar-t-3">图片最大尺寸限制为750×640</div>
            <el-upload
              list-type="picture-card"
              action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp"
              name="files"
              :data="token"
              :show-file-list="false"
              v-loading="fileLoading"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
              <img v-if="coupon.imageUrl" :src="coupon.imageUrl" style="width: 145px;height: 145px">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
      </div>
      <h2 class="pad-t-20">使用规则</h2>
      <div class="bg-color-white pad-t-30 pad-b-30">
        <el-form-item label="优惠叠加" prop="originalPriceFlag">
          <div class="width-per-50">
            <el-checkbox v-model="coupon.originalPriceFlag" true-label="1" false-label="0">优惠券仅原价购买商品时可使用</el-checkbox>
            <div class="font-12">勾选时，如果商品参与了其他营销活动，如秒杀、包邮等，则券不可用。</div>
          </div>
        </el-form-item>
        <el-form-item label="使用规则" prop="ruleInfo">
          <div class="width-per-50">
            <Tinymce ref="editor" style="width: 100%" v-model="coupon.ruleInfo" :showUploadBtn="false" menubar="false" :toolbar="toolbar" />
          </div>
        </el-form-item>
      </div>
    </el-form>

    <div v-if="editFlag == 1" class="bottom-bar">
      <el-button @click="goCouponList">取消</el-button>
      <el-button type="primary" @click="saveCoupon">确定</el-button>
    </div>

    <el-dialog title="选择商品" :visible.sync="selectGoodsVisible" :close-on-press-escape="true" width="850px">
      <goods-select :goodsIds="coupon.goodsRange == 2 ? coupon.useGoodsIds : coupon.notUseGoodsIds" v-on:saveGoodsIds="saveGoodsIds"></goods-select>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.bgc-default{
  padding-bottom: 110px;
  h2{
    font-size: 20px;
    color: #666;
    line-height: 1;
    margin: 0 0 20px;
    font-weight: unset;
  }
  .bottom-bar{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 110px;
    position: fixed;
    left: 0;
    bottom: 0;
    width: calc(100% - 20px);
    box-shadow: 0 -2px 12px #eee;
    background-color: white;
    .el-button{
      width: 100px;
      height: 40px;
      line-height: 40px;
      padding: unset;
      text-align: center;
    }
    .el-button+.el-button{
      margin-left: 30px;
    }
  }
}
  .div-styls{
    margin-top: 30px;
    margin-bottom: 20px;
  }
  .mini-pic {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
  .width-per-50{
    width: 48%;
    margin-left: 1%!important;
    margin-right: 1%!important;
    background: #fff;
  }
</style>

<script>
  import { getCoupon, saveCoupon } from '@/api/coupon/coupon'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'
  import GoodsSelect from '../components/GoodsSelect'
  import Tinymce from '@/components/Tinymce'
  import { getToken } from '@/utils/auth'

  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    components: {
      Tinymce, GoodsSelect
    },
    data() {
      return {
        toolbar: ['bold italic underline forecolor bullist numlist undo redo'],
        dict: {},
        coupon: {
          enterpriseId: this.getEnterpriseId(),
          couponStatus: '0',
          couponType: '0',
          fullAmountFlag: '0',
          limitFlag: '1',
          goodsRange: '1',
          validTimeType: '1',
          originalPriceFlag: '0',
          validTimeArray: [],
          couponName: '',
          cashAmount: '',
          fullAmount: '',
          reduceAmount: '',
          discountPercent: '',
          couponRemark: '',
          couponNum: '',
          validFromToday: '',
          validFromTomorrow: '',
          ruleInfo: '',
          goodsIds: [],
          useGoodsIds: [],
          notUseGoodsIds: []
        },
        token: '',
        fileLoading: false,
        validTimeArrayDisabled: false,
        validFromTodayDisabled: true,
        validFromTomorrowDisabled: true,
        couponNumDisabled: false,
        fullAmountDisabled: false,
        selectGoodsVisible: false,
        useGoodsDisabled: true,
        notToUseGoodsDisabled: true,
        editFlag: '0',
        rules: {
          couponName: [
            { required: true, message: '券名称不能为空', trigger: 'blur' }
          ],
          cashAmount: [
            { required: true, message: '面值不能为空', trigger: 'blur' }
          ],
          reduceAmount: [
            { required: true, message: '优惠方式不能为空', trigger: 'blur' }
          ],
          fullAmountFlag: [
            { required: true, message: '使用条件不能为空', trigger: 'blur' }
          ],
          discountPercent: [
            { required: true, message: '优惠方式不能为空', trigger: 'blur' }
          ],
          limitFlag: [
            { required: true, message: '发放数量不能为空', trigger: 'blur' }
          ],
          goodsRange: [
            { required: true, message: '适用商品不能为空', trigger: 'blur' }
          ],
          couponRemark: [
            { required: true, message: '使用范围说明不能为空', trigger: 'blur' }
          ],
          validTimeType: [
            { required: true, message: '有效时间不能为空', trigger: 'blur' }
          ],
          imageUrl: [
            { required: true, message: '封面图不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    // 初始化页面
    created() {
      getDictByGroupName('ProjectOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      this.token = { accessToken: getToken() }
      this.init()
    },
    mounted() {
    },
    methods: {
      init() {
        const queryParams = this.getCurrentPage().query
        this.editFlag = queryParams.editFlag
        this.coupon.couponType = queryParams.couponType
        if (queryParams.couponId) {
          getCoupon(queryParams.couponId).then(response => {
            if (response.isError) {
              return
            }
            Object.assign(this.coupon, response.data)
            this.coupon.couponStatus = this.coupon.couponStatus.toString()
            this.coupon.couponType = this.coupon.couponType.toString()
            this.coupon.fullAmountFlag = this.coupon.fullAmountFlag.toString()
            this.coupon.limitFlag = this.coupon.limitFlag.toString()
            this.coupon.goodsRange = this.coupon.goodsRange.toString()
            this.coupon.validTimeType = this.coupon.validTimeType.toString()
            if (this.coupon.validTimeType === '1') {
              this.coupon.validTimeArray.push(this.coupon.validStartTime)
              this.coupon.validTimeArray.push(this.coupon.validEndTime)
            }
            this.coupon.originalPriceFlag = this.coupon.originalPriceFlag.toString()
            if (this.coupon.goodsRange * 1 === 1) {
              this.useGoodsDisabled = true
              this.notToUseGoodsDisabled = true
            }
            if (this.coupon.goodsRange * 1 === 2) {
              this.useGoodsDisabled = false
              this.coupon.useGoodsIds = this.coupon.goodsIds
              this.notToUseGoodsDisabled = true
            }
            if (this.coupon.goodsRange * 1 === 3) {
              this.useGoodsDisabled = true
              this.notToUseGoodsDisabled = false
              this.coupon.notUseGoodsIds = this.coupon.goodsIds
            }
            this.$bus.$emit('setGoodsIds', this.coupon.goodsIds)
            this.changeFullAmountFlag()
            this.changeLimitFlag()
            this.changeGoodsRange()
            this.changeValidTimeType()
          })
        }
      },
      showUseGoodsDialog() {
        // this.$bus.$emit('setGoodsIds', this.coupon.useGoodsIds)
        this.selectGoodsVisible = true
      },
      showNotUseGoodsDialog() {
        // this.$bus.$emit('setGoodsIds', this.coupon.notUseGoodsIds)
        this.selectGoodsVisible = true
      },
      saveGoodsIds(goodsIds) {
        this.coupon.goodsIds = goodsIds
        if (this.coupon.goodsRange * 1 === 2) {
          this.coupon.useGoodsIds = Array.from(this.coupon.goodsIds)
        }
        if (this.coupon.goodsRange * 1 === 3) {
          this.coupon.notUseGoodsIds = Array.from(this.coupon.goodsIds)
        }
        this.selectGoodsVisible = false
      },
      saveCoupon() {
        let validateResult = true
        const checkArrays = ['couponName', 'limitFlag', 'goodsRange', 'couponRemark', 'validTimeType']
        if (this.coupon.couponType * 1 === 10) {
          checkArrays.push('cashAmount')
        }
        if (this.coupon.couponType * 1 === 20) {
          checkArrays.push('reduceAmount')
        }
        if (this.coupon.couponType * 1 === 30) {
          checkArrays.push('fullAmountFlag')
          checkArrays.push('discountPercent')
        }
        this.$refs.coupon.validateField(checkArrays, (valid) => {
          if (valid) {
            validateResult = false
          }
        })
        if (!validateResult) {
          return
        }
        if (this.coupon.ruleInfo.length > 120) {
          this.$message.error('使用规则说明字数不可多于120个字')
          return
        }
        if (this.coupon.couponType * 1 === 10 && this.coupon.cashAmount * 1 === 0) {
          this.$message.error('面值不能为0')
          return
        }
        if (this.coupon.couponType * 1 === 20) {
          if (!this.coupon.fullAmount) {
            this.$message.error('请输入满减金额')
            return
          }
          if (this.coupon.fullAmount * 1 <= this.coupon.reduceAmount * 1) {
            this.$message.error('立减金额必须小于单笔订单满金额')
            return
          }
        }
        if (this.coupon.couponType * 1 === 30) {
          if (this.coupon.fullAmountFlag * 1 === 0 && !this.coupon.fullAmount) {
            this.$message.error('请输入单笔订单金额')
            return
          }
          if (this.coupon.fullAmountFlag * 1 === 0 && this.coupon.fullAmount * 1 === 0) {
            this.$message.error('单笔订单金额必须大于0')
            return
          }
          if (this.coupon.discountPercent * 1 <= 0 || this.coupon.discountPercent * 1 >= 10) {
            this.$message.error('折扣值要在0~10之间')
            return
          }
        }
        if (this.coupon.limitFlag * 1 === 1 && !this.coupon.couponNum) {
          this.$message.error('请输入大于0的券发放总数量')
          return
        }
        if (this.coupon.goodsRange * 1 !== 1 && !this.coupon.goodsIds) {
          this.$message.error('请先选择商品')
          return
        }
        if (this.coupon.validTimeType * 1 === 1 && this.coupon.validTimeArray.length < 2) {
          this.$message.error('请先选择有效时间范围')
          return
        }
        if (this.coupon.validTimeType * 1 === 2 && !this.coupon.validFromToday) {
          this.$message.error('请填入最少为1天的天数')
          return
        }
        if (this.coupon.validTimeType * 1 === 3 && !this.coupon.validFromTomorrow) {
          this.$message.error('请填入最少为1天的天数')
          return
        }

        if (this.coupon.validTimeType * 1 === 1) {
          this.coupon.validStartTime = this.coupon.validTimeArray[0]
          this.coupon.validEndTime = this.coupon.validTimeArray[1]
        }
        this.coupon.availableNum = this.coupon.couponNum

        saveCoupon(this.coupon).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          this.$router.push({ path: '/sell-promotion/coupon/list' })
        })
      },
      goCouponList() {
        this.$router.push({ path: '/sell-promotion/coupon/list' })
      },
      changeFullAmountFlag() {
        if (this.coupon.fullAmountFlag * 1 === 1) {
          this.coupon.fullAmount = ''
          this.fullAmountDisabled = true
        } else {
          this.fullAmountDisabled = false
        }
      },
      changeLimitFlag() {
        if (this.coupon.limitFlag * 1 === 0) {
          this.coupon.couponNum = ''
          this.couponNumDisabled = true
        } else {
          this.couponNumDisabled = false
        }
      },
      changeGoodsRange() {
        if (this.coupon.goodsRange * 1 === 1) {
          this.useGoodsDisabled = true
          this.notToUseGoodsDisabled = true
        }
        if (this.coupon.goodsRange * 1 === 2) {
          this.coupon.goodsIds = Array.from(this.coupon.useGoodsIds)
          this.$bus.$emit('setGoodsIds', this.coupon.useGoodsIds)
          this.useGoodsDisabled = false
          this.notToUseGoodsDisabled = true
        }
        if (this.coupon.goodsRange * 1 === 3) {
          this.coupon.goodsIds = Array.from(this.coupon.notUseGoodsIds)
          this.$bus.$emit('setGoodsIds', this.coupon.notUseGoodsIds)
          this.useGoodsDisabled = true
          this.notToUseGoodsDisabled = false
        }
      },
      changeValidTimeType() {
        if (this.coupon.validTimeType * 1 === 1) {
          this.validTimeArrayDisabled = false
          this.validFromTodayDisabled = true
          this.validFromTomorrowDisabled = true
        }
        if (this.coupon.validTimeType * 1 === 2) {
          this.validFromTodayDisabled = false
          this.validTimeArrayDisabled = true
          this.validFromTomorrowDisabled = true
        }
        if (this.coupon.validTimeType * 1 === 3) {
          this.validFromTomorrowDisabled = false
          this.validTimeArrayDisabled = true
          this.validFromTodayDisabled = true
        }
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        this.fileLoading = false
        if (res.code === 101) {
          this.coupon.imageUrl = res.data[0]
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      }
    }
  }

</script>
